const cloud = require('wx-server-sdk')
const envid = 'edu-sdust-0gcxtlev1c3c5887'

cloud.init({
  env:envid
})
const timeutil = require('./timeutil');
const db = cloud.database();
const _ = db.command;
const ORDER_TABLE = 'SDUST_ORDER';
//订单表
exports.main = async (event, context) => {
  var fee = parseInt(event.fee);
  let paydata = event.paydata;
  let tradeno = GetTradeNo();
  const res = await cloud.cloudPay.unifiedOrder({
    "body": "山科付费项目",
    "outTradeNo": tradeno,
    "spbillCreateIp": "127.0.0.1",
    "subMchId": "1608692095",
    "totalFee": fee,
    "envId": envid,
    "functionName": "unipaynotify"
  })
  //定义订单状态
  //保存订单号码
  paydata.date = timeutil.TimeCode() //订单生成time
  paydata.orderid = tradeno
  paydata.fee = event.fee //parseFloat
  paydata.orderstatus = 0
  paydata.wxorder = res
  if(res.returnCode=='SUCCESS' && res.resultCode=='SUCCESS'){
    //如果签名成功,写入订单表
    db.collection(ORDER_TABLE).add({
      data:paydata
    })
  }
  
  return res
}

function GetTradeNo() {
  var outTradeNo = ""; //订单号
  for (var i = 0; i < 6; i++) //6位随机数，用以加在时间戳后面。
  {
    outTradeNo += Math.floor(Math.random() * 10);
  }
  outTradeNo = "SDUST" + new Date().getTime() + outTradeNo; //时间戳，用来生成订单号。
  return outTradeNo;
}
function TimeCode() {
  var date = new Date();
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function TimeCodeYmd(){
  var date = new Date();
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  return [year, month, day].map(formatNumber).join('-');
}
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}